using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Animation;
using System.Threading.Tasks;
using KarliCardsGui.ViewModels;
using System.Windows.Threading;
using System.Windows.Media;
using KarliCardsGui.constants;
using KarliCardsGui.Converters;

namespace KarliCardsGui.Animations
{
    public class ShuffleAnimator
    {
        private readonly Random random = new Random();

        public async Task AnimateShuffleAsync(List<CardViewModel> cards)
        {
            // 第一阶段：所有牌移动到右上角（从最后一张开始）
            var tasks = new List<Task>();
            for (int i = cards.Count - 1; i >= 0; i--)
            {
                tasks.Add(AnimateCardToCornerAsync(cards[i]));
                await Task.Delay(20);
            }
            await Task.WhenAll(tasks);
            
            // 洗牌
            for (int i = cards.Count - 1; i > 0; i--)
            {
                int j = random.Next(i + 1);
                CardViewModel temp = cards[i];
                cards[i] = cards[j];
                cards[j] = temp;
            }


            // 更换背景并等待一小段时间让界面更新
            RandomCardBackConverter.ChangeBackground();

            foreach (CardViewModel oneViewModel in cards)
            {
                oneViewModel.IsFaceUp = false;
            }
            await Task.Delay(300);

            // 第二阶段：所有牌回到原位
            tasks.Clear();
            for (int i = 0; i < cards.Count; i++)
            {
                cards[i].YPosition = Constants.CardStackPositionY + i * Constants.CardStackOffsetY;
                cards[i].ZIndex = i;
                tasks.Add(AnimateCardBackAsync(cards[i]));
                await Task.Delay(20);
            }
            await Task.WhenAll(tasks);
        }

        private Task AnimateCardToCornerAsync(CardViewModel card)
        {
            var tcs = new TaskCompletionSource<bool>();
            double startX = card.XPosition;
            double startY = card.YPosition;
            double endX = Constants.CardShuffleDestX;
            double endY = Constants.CardShuffleDestY;
            DateTime startTime = DateTime.Now;
            int duration = Constants.ShuffleAnimationDuration;

            CompositionTarget.Rendering += AnimationTick;

            void AnimationTick(object sender, EventArgs e)
            {
                double elapsed = (DateTime.Now - startTime).TotalMilliseconds;
                if (elapsed >= duration)
                {
                    card.XPosition = endX;
                    card.YPosition = endY;
                    CompositionTarget.Rendering -= AnimationTick;
                    tcs.SetResult(true);
                }
                else
                {
                    double progress = elapsed / duration;
                    card.XPosition = startX + (endX - startX) * progress;
                    card.YPosition = startY + (endY - startY) * progress;
                }
            }

            return tcs.Task;
        }

        private Task AnimateCardBackAsync(CardViewModel card)
        {
            var tcs = new TaskCompletionSource<bool>();

            double startX = Constants.CardShuffleDestX;
            double startY = Constants.CardShuffleDestY;
            double endX = Constants.CardStackPositionX;
            double endY = card.YPosition;
            DateTime startTime = DateTime.Now;
            int duration = Constants.ShuffleAnimationDuration;

            CompositionTarget.Rendering += AnimationTick;

            void AnimationTick(object sender, EventArgs e)
            {
                double elapsed = (DateTime.Now - startTime).TotalMilliseconds;
                if (elapsed >= duration)
                {
                    card.XPosition = endX;
                    card.YPosition = endY;
                    CompositionTarget.Rendering -= AnimationTick;
                    tcs.SetResult(true);
                }
                else
                {
                    double progress = elapsed / duration;
                    card.XPosition = startX + (endX - startX) * progress;
                    card.YPosition = startY + (endY - startY) * progress;
                }
            }

            return tcs.Task;
        }
    }
} 